//当该app是提供给B2B2C或存在供应商时,从setup里调取该组件
'use strict';
import React,{Component} from 'react';
import Header from '../common/header';
import Util from '../common/util';
import styles from '../style/styles';
import Icon from 'react-native-vector-icons';
import FIcon from 'react-native-vector-icons';
import GoodsInfo from '../goods/goodsIndex';
import CheckBoxModel from '../common/checkboxmodel';
import * as URLconstant from '../constant/URLconstant'
import Toast from '../common/ToastUtil'
import ConfirmOrder from '../order/confirmOrder'
import {
    View,
    Text,
    TouchableOpacity,
    Image,
    ScrollView,
    TextInput,
    Platform
} from 'react-native';
var CheckBoxData = [];
var CheckBoxData1 = [];

export default class supplierShoppingCart extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        //this.successGetgood=this.successGetgood.bind(this)
        this.successDelete = this.successDelete.bind(this)
        this.errorCallback = this.errorCallback.bind(this)
        this.successNumAdd = this.successNumAdd.bind(this)
        this.deleteGoods=this.deleteGoods.bind(this)
        this.allSelect=this.allSelect.bind(this)
        this.checkSelect=this.checkSelect.bind(this)
       // this.successGetgood=this.successGetgood.bind(this)
        this.state = {
            titleType: 1,
            CartGoodsList: ['1'],
            isSelectAll: false,
            CheckBoxData1: [],
            price:0

        };
    }

    componentDidMount() {
        if (this.props.titleType == 2) {
            this.setState({
                titleType: 2
            })
        }
    }

    errorCallback(err) {
        LOG(err)
    }

    //删除购物车调用
    deleteGoods(shopping_id,goodsprice,quantity) {
        let context = this;
        if (shopping_id != '' || shopping_id != null) {
            context.setState({shopping_id: shopping_id,goodsprice:goodsprice,quantity:quantity});
            let datas = context.props.datas;
            let data = this.props.data;
            let user_id = data.user_id;
            let dataDelete = [];
            dataDelete['user_id'] = user_id;
            dataDelete['shopping_id'] = shopping_id;
            let deleteURL = URLconstant.DELETECART_URL;
            Util.post(deleteURL, dataDelete, context.successDelete, context.errorCallback);
        }


    }

    //删除请求成功
    successDelete(datas) {
        let shopping_id=this.state.shopping_id;
        let goodsprice=this.state.goodsprice
        let price=this.state.price
        let quantity=this.state.quantity
       // LOG(datas)
        let data = this.props.data;
        let user_id = data.user_id;
        if (datas.status == 0) {
            this.props.onLoginSuccess1(user_id)
            Toast.show(datas.msg)
            for (let i in CheckBoxData) {
                if (CheckBoxData[i] == shopping_id) {
                    CheckBoxData.splice(i, 1)
                    price=price-parseFloat(goodsprice)*quantity
                }

            }
            this.setState({
                price:price
            })
            //LOG(CheckBoxData)
        }
    }


    checkSelect(checked, shopping_id,goodsprice,quantity) {
        //LOG('checked===='+checked)
        let price=this.state.price
        if (checked == true) {
           // LOG('选中')
            CheckBoxData.push(shopping_id)
            price=price+parseFloat(goodsprice)*quantity;
            //LOG(price)
            this.setState({
                price:price
            })
            //LOG(CheckBoxData)
        } else {
           // LOG('取消')
            price=price-parseFloat(goodsprice)*quantity;
            //LOG(price)
            this.setState({
                isSelectAll: false,
                price:price
            })
            for (let i in CheckBoxData) {
                if (CheckBoxData[i] == shopping_id) {
                    CheckBoxData.splice(i, 1)
                }

            }
            //LOG(CheckBoxData)
        }


    }

    initCheckBoxData(checkbox) {


        if (checkbox != null) {
            CheckBoxData1.push(checkbox);
        }
    }

    //全选
    allSelect() {
        let data = this.props.data;
        let goods_list = data.goods_list;
        CheckBoxData = []
        let price=0
        if (this.state.isSelectAll) {

            this.setState({
                isSelectAll: false,
                price:0
            })
            //LOG(CheckBoxData)
        } else {
            for (let i in goods_list) {
                let shopping_id = goods_list[i].shopping_id
                CheckBoxData.push(shopping_id)
                price=price+parseFloat(goods_list[i].price)*goods_list[i].quantity
            }
            //LOG(CheckBoxData)

            this.setState({
                isSelectAll: !this.state.isSelectAll,
                price:price
            })
        }
        for (let item of CheckBoxData1) {
            item.onChange(!this.state.isSelectAll)
        }

    }

    //改变数量
    buyNUmAddorDel(buyNum, shopping_id, text,goodsprice) {
        let number = parseInt(buyNum);
        let price=this.state.price
        if (text == 'del') {
            if (number == 1) {
                return;
            }
            price=price-parseFloat(goodsprice);
            number--;
        } else if (text == 'add') {
            number++;
            price=price+parseFloat(goodsprice);
        } else {
            var value = text
            var reg = /^\d+(\.\d+)?$/;
            if (reg.test(value) == true) {
                if (parseInt(text) >= 0) {
                    number = parseInt(text);
                }
            } else {
                if (text == '' || text == 0) {
                    alert("请输入大于0的数量");

                } else {
                    alert("请输入正确的数量");
                }

                return false
            }

        }
        for (let i in CheckBoxData) {
            //LOG(CheckBoxData[i]+'+++++++'+shopping_id)
            if(CheckBoxData[i]==shopping_id){
                this.setState({
                    price:price
                })
            }
        }

        let data = this.props.data;
        let user_id = data.user_id;
        let datakey = [];
        datakey['user_id'] = user_id;
        datakey['shopping_id'] = shopping_id;
        datakey['quantity'] = number;
        let NUmAddUrl = URLconstant.CARTNUMBER_URL;
        Util.post(NUmAddUrl, datakey, this.successNumAdd, this.errorCallback)
    }


    successNumAdd(datas) {
        //LOG(datas)
        let data = this.props.data;
        let user_id = data.user_id;
        if (datas.status == 0) {
            this.props.onLoginSuccess1(user_id)
            Toast.show(datas.msg)

        }
    }


    goodsInfo(goods_id) {
        let that = this;
        that.props.navigator.push({
            component: GoodsInfo,
            passProps: {
                goods_id: goods_id
            }
        })
    }

//购物车结算
    goGetGoods(){
        let getGoodsurl=URLconstant.GETCARTGOODS_URL;
        let datakey=[];
        let data = this.props.data;
        let user_id = data.user_id;
        datakey['user_id']=user_id;
        if(CheckBoxData==''||CheckBoxData==[]){
            Toast.show('请先选择商品')

        }else {
            let list=CheckBoxData.toString()
            this.props.navigator.push({
                component: ConfirmOrder,
                passProps: {
                    list: list,
                    user_id:user_id,
                    type:1
                }
            })
        }

    }

    cartGoods() {
        let that = this;
        let data = this.props.data
        let goods_list = data.goods_list
        let rows;
        let list = [];
        if (goods_list.length == 0) {
            return (
                <ScrollView style={styles.bg_scrollview}>
                    <View style={styles.cart_no_wrap}>
                        <FIcon name={'shopping-cart'} size={150} color={'#aaa'}/>
                        <Text style={styles.cart_no_txt1}>购物车没有商品哦</Text>
                        <Text style={styles.cart_no_txt2}>快去添加吧</Text>
                    </View>
                </ScrollView>
            )
        }
        for (let i = 0; i < goods_list.length; i++) {
            //LOG('goods_list[i].goods_img==='+goods_list[i].goods_img)
            rows = (
                <View style={styles.cart_goods_wrap} key={i}>
                    <CheckBoxModel
                        ref={(c)=>that.initCheckBoxData(c)}
                        label=""
                        checked={false}
                        value={goods_list[i].shopping_id}
                        onChange={(checked) => that.checkSelect(checked,goods_list[i].shopping_id,goods_list[i].price,goods_list[i].quantity)}/>
                    <TouchableOpacity onPress={()=>this.goodsInfo(goods_list[i].goods_id)}>
                        <Image
                            resizeMode="stretch"
                            style={styles.cart_img}
                            source={{uri:goods_list[i].goods_img}}/>
                    </TouchableOpacity>
                    <View style={styles.cart_wrap_right}>
                        <Text style={styles.cart_goods_title}>{goods_list[i].goods_name}</Text>
                        <View style={styles.cart_bottom}>
                            <Text style={styles.cart_goods_price}>价格:￥{goods_list[i].price}</Text>
                            <View style={styles.cart_del_add}>
                                <TouchableOpacity style={styles.del_add}
                                                  onPress={()=>this.buyNUmAddorDel(goods_list[i].quantity,goods_list[i].shopping_id,'del',goods_list[i].price)}>
                                    <Text>-</Text>
                                </TouchableOpacity>
                                {Platform.OS === 'android' ?
                                    <TextInput
                                        style={styles.cart_num_input_and}
                                        underlineColorAndroid={'transparent'}
                                        placeholder={goods_list[i].quantity+''}
                                        placeholderTextColor={'#333'}
                                        multiline={false}
                                        editable={false}
                                        autoCorrect={false}
                                        keyboardType='numeric'
                                        defaultValue={goods_list[i].quantity+''}
                                        enablesReturnKeyAutomatically={true}
                                        onChangeText={(text) => this.buyNUmAddorDel(goods_list[i].quantity,goods_list[i].shopping_id, text) }
                                        returnKeyType='next'
                                    />
                                    :
                                    <TextInput
                                        style={styles.cart_num_input}
                                        underlineColorAndroid={'transparent'}
                                        placeholder={goods_list[i].quantity+''}
                                        placeholderTextColor={'#333'}
                                        multiline={false}
                                        editable={false}
                                        autoCorrect={false}
                                        keyboardType='numeric'
                                        defaultValue={goods_list[i].quantity}
                                        enablesReturnKeyAutomatically={true}
                                        onChangeText={(text) => this.buyNUmAddorDel(goods_list[i].quantity,goods_list[i].shopping_id, text) }
                                        returnKeyType='next'
                                    />
                                }
                                <TouchableOpacity style={styles.del_add}
                                                  onPress={()=>this.buyNUmAddorDel(goods_list[i].quantity,goods_list[i].shopping_id,'add',goods_list[i].price)}>
                                    <Text>+</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                        <TouchableOpacity style={styles.cart_delete_goods}
                                          onPress={()=>this.deleteGoods(goods_list[i].shopping_id,goods_list[i].price,goods_list[i].quantity)}>
                            <Icon name={'md-trash'} size={20} color={'#aaa'}/>
                        </TouchableOpacity>
                    </View>
                </View>
            )
            list.push(rows);
        }
        return (
            <View style={{flex:1,}}>
                <ScrollView style={styles.bg_scrollview}>
                    <View style={{minHeight:Util.size.height-200}}>
                        {list}
                    </View>

                </ScrollView>
                {this.cartBtn()}
            </View>
        )

    }

    //购物车底部全选丶结算按钮
    cartBtn() {
        let data = this.props.data;
        let total = data.total
        return (
            <View style={styles.cart_btn}>
                <View style={styles.btn_left}>
                    <TouchableOpacity style={styles.btn_left} onPress={()=>this.allSelect()}>
                        {this.state.isSelectAll ?
                            <Icon name={'md-checkmark-circle'} size={20} color={'#f00'}/>
                            :
                            <Icon name={'ios-radio-button-off-outline'} size={20} color={'#333'}/>
                        }

                        <Text>全选</Text>
                    </TouchableOpacity>
                    <Text style={styles.cart_price}>总额:￥{this.state.price}</Text>
                </View>
                <TouchableOpacity style={styles.btn_right} onPress={()=>this.goGetGoods()}>
                    <Text style={styles.btn_right_txt}>去结算</Text>
                </TouchableOpacity>
            </View>
        )
    }

    render() {
        return (
            <View style={{flex:1}}>
                <Header navigator={this.props.navigator} initObj={{ title: '购物车',id:this.state.titleType}}/>
                {this.cartGoods()}
            </View>
        )
    }
}